package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.PowerFailedException;
import com.jixi.common.result.PageResult;
import com.jixi.common.result.Result;
import com.jixi.mapper.CompanyMapper;
import com.jixi.mapper.CooperateSchoolCompanyMapper;
import com.jixi.mapper.EducationMapper;
import com.jixi.mapper.SchoolMapper;
import com.jixi.pojo.dto.AddCooperateDto;
import com.jixi.pojo.entity.Company;
import com.jixi.pojo.entity.CooperateSchoolCompany;
import com.jixi.pojo.entity.Education;
import com.jixi.pojo.entity.School;
import com.jixi.pojo.vo.CooperateSchoolCompanyListVO;
import com.jixi.service.CooperateSchoolCompanyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CooperateSchoolCompanyServiceImpl extends ServiceImpl<CooperateSchoolCompanyMapper, CooperateSchoolCompany> implements CooperateSchoolCompanyService {
	
	@Autowired
	private CooperateSchoolCompanyMapper cooperateSchoolCompanyMapper;
	
	@Autowired
	private EducationMapper educationMapper;
	
	@Autowired
	private SchoolMapper schoolMapper;
	
	@Autowired
	private CompanyMapper companyMapper;
	
	/**
	 * 获取餐饮公司的启用合作数
	 *
	 * @param companyId 餐饮公司id
	 * @return 餐饮公司合作数
	 */
	@Override
	public Long countCompanyCooperateNum(Long companyId) {
		
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper = new LambdaQueryWrapper<>();
		//查正在合作的（启用）
		queryWrapper.eq(CooperateSchoolCompany::getStatus, 1);
		//查未删除的
		queryWrapper.eq(CooperateSchoolCompany::getIsDeleted, 0);
		queryWrapper.eq(CooperateSchoolCompany::getCompanyId, companyId);
		return cooperateSchoolCompanyMapper.selectCount(queryWrapper);
	}
	
	/**
	 * 合作关系条件列表分页查询
	 *
	 * @param pageNum   页码
	 * @param pageSize  每页数量
	 * @param schoolId  学校id
	 * @param companyId 餐饮公司id
	 * @param status    状态
	 * @return 学校列表
	 */
	@Override
	public Result<PageResult> cooperatePage(
			Integer pageNum,
			Integer pageSize,
			Long schoolId,
			Long companyId,
			Integer status
	) {
		//分页构造器
		Page<CooperateSchoolCompany> pageInfo = new Page<>(pageNum, pageSize);
		
		//条件构造器
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper.eq(CooperateSchoolCompany::getIsDeleted, 0);
		//添加可能有的过滤条件
		queryWrapper.eq(schoolId != null, CooperateSchoolCompany::getSchoolId, schoolId);
		queryWrapper.eq(companyId != null, CooperateSchoolCompany::getCompanyId, companyId);
		queryWrapper.eq(status != null, CooperateSchoolCompany::getStatus, status);
		//根据更新时间降序排序
		queryWrapper.orderByDesc(CooperateSchoolCompany::getUpdateTime);
		
		//执行分页查询
		cooperateSchoolCompanyMapper.selectPage(pageInfo, queryWrapper);
		
		//处理名字信息
		List<CooperateSchoolCompanyListVO> cooperateSchoolCompanyList = pageInfo.getRecords().stream()
				.map(cooperateSchoolCompany -> {
					CooperateSchoolCompanyListVO vo = new CooperateSchoolCompanyListVO();
					BeanUtils.copyProperties(cooperateSchoolCompany, vo); //使用Spring的Bean工具类复制属性
					
					Long schoolId1 = vo.getSchoolId();
					School school = schoolMapper.selectById(schoolId1);
					if (school == null || school.getIsDeleted() == 1) {
						vo.setSchoolName("该学校不存在");
					} else if (school.getStatus() == 0) {
						vo.setSchoolName(school.getSchoolName() + "（该学校已停用）");
					} else {
						vo.setSchoolName(school.getSchoolName());
					}
					
					Long companyId1 = vo.getCompanyId();
					Company company = companyMapper.selectById(companyId1);
					if (company == null || company.getIsDeleted() == 1) {
						vo.setCompanyName("该餐饮公司不存在");
					} else if (company.getStatus() == 0) {
						vo.setCompanyName(company.getCompanyName() + "（该餐饮公司已停用）");
					} else {
						vo.setCompanyName(company.getCompanyName());
					}
					
					return vo;
				}).collect(Collectors.toList());
		
		//处理分页信息
		PageResult pageResult = new PageResult(pageInfo.getTotal(), cooperateSchoolCompanyList);
		return Result.success(pageResult);
	}
	
	/**
	 * 添加合作关系
	 *
	 * @param addCooperateDto 学校合作餐饮公司信息
	 * @return 添加结果
	 */
	@Override
	public Result addCooperate(AddCooperateDto addCooperateDto) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		Long schoolId = addCooperateDto.getSchoolId();
		Long companyId = addCooperateDto.getCompanyId();
		
		//先检查有没有重复的
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(CooperateSchoolCompany::getIsDeleted, 0);
		queryWrapper1.eq(CooperateSchoolCompany::getSchoolId, schoolId);
		queryWrapper1.eq(CooperateSchoolCompany::getCompanyId, companyId);
		Long count = cooperateSchoolCompanyMapper.selectCount(queryWrapper1);
		if (count > 0) {
			return Result.fail("添加失败，已有该合作关系");
		}
		
		//判断学校和餐饮公司是否存在及判断状态
		LambdaQueryWrapper<School> queryWrapperSchool = new LambdaQueryWrapper<>();
		queryWrapperSchool.eq(School::getSchoolId, schoolId);
		queryWrapperSchool.eq(School::getIsDeleted, 0);
		School school = schoolMapper.selectOne(queryWrapperSchool);
		if (school == null) {
			return Result.fail("添加失败，该学校不存在");
		}
		if(school.getStatus() == 0){
			return Result.fail("添加失败，该学校已停用");
		}
		LambdaQueryWrapper<Company> queryWrapperCompany = new LambdaQueryWrapper<>();
		queryWrapperCompany.eq(Company::getCompanyId, companyId);
		queryWrapperCompany.eq(Company::getIsDeleted, 0);
		Company company = companyMapper.selectOne(queryWrapperCompany);
		if (company == null) {
			return Result.fail("添加失败，该餐饮公司不存在");
		}
		if(company.getStatus() == 0){
			return Result.fail("添加失败，该餐饮公司已停用");
		}
		
		//执行添加
		CooperateSchoolCompany cooperateSchoolCompany = new CooperateSchoolCompany();
		cooperateSchoolCompany.setSchoolId(schoolId);
		cooperateSchoolCompany.setCompanyId(companyId);
		cooperateSchoolCompany.setIsDeleted(0);
		cooperateSchoolCompanyMapper.insert(cooperateSchoolCompany);
		
		return Result.success("添加成功");
	}
	
	/**
	 * 修改合作关系状态
	 *
	 * @param cooperateId 合作关系id
	 * @param status      状态
	 * @return 修改结果
	 */
	@Override
	public Result updateCooperateStatus(Long cooperateId, Integer status) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		if (status != 1 && status != 0) {
			return Result.fail("状态值有误");
		}
		
		//执行修改
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(CooperateSchoolCompany::getIsDeleted, 0);
		queryWrapper1.eq(CooperateSchoolCompany::getCooperateId, cooperateId);
		CooperateSchoolCompany cooperate = cooperateSchoolCompanyMapper.selectOne(queryWrapper1);
		
		//先查学校和餐饮公司的状态
		LambdaQueryWrapper<School> queryWrapperSchool = new LambdaQueryWrapper<>();
		queryWrapperSchool.eq(School::getSchoolId, cooperate.getSchoolId());
		queryWrapperSchool.eq(School::getIsDeleted, 0);
		queryWrapperSchool.eq(School::getStatus, 1);
		if (schoolMapper.selectCount(queryWrapperSchool) == null || schoolMapper.selectCount(queryWrapperSchool) == 0) {
			return Result.fail("合作状态修改失败，学校不存在或已被停用");
		}
		LambdaQueryWrapper<Company> queryWrapperCompany = new LambdaQueryWrapper<>();
		queryWrapperCompany.eq(Company::getCompanyId, cooperate.getCompanyId());
		queryWrapperCompany.eq(Company::getIsDeleted, 0);
		queryWrapperCompany.eq(Company::getStatus, 1);
		if (companyMapper.selectCount(queryWrapperCompany) == null || companyMapper.selectCount(queryWrapperCompany) == 0) {
			return Result.fail("合作状态修改失败，餐饮公司不存在或已被停用");
		}
		
		cooperate.setStatus(status);
		cooperate.setUpdateTime(DateTime.now());
		cooperateSchoolCompanyMapper.insertOrUpdate(cooperate);
		
		return Result.success("状态修改成功");
	}
	
	/**
	 * 删除合作关系
	 *
	 * @param cooperateId 合作表id
	 * @return 删除结果
	 */
	@Override
	public Result deleteCooperateById(Long cooperateId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		//假删除
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(CooperateSchoolCompany::getCooperateId, cooperateId);
		CooperateSchoolCompany cooperateSchoolCompany = cooperateSchoolCompanyMapper.selectOne(queryWrapper1);
		cooperateSchoolCompany.setIsDeleted(1);
		cooperateSchoolCompany.setUpdateTime(DateTime.now());
		cooperateSchoolCompanyMapper.insertOrUpdate(cooperateSchoolCompany);
		
		return Result.success("删除成功");
	}
	
	/**
	 * 获取学校的启用合作数
	 *
	 * @param schoolId 学校id
	 * @return 学校合作数
	 */
	@Override
	public Long countSchoolCooperateNum(Long schoolId) {
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper = new LambdaQueryWrapper<>();
		//查正在合作的（启用）
		queryWrapper.eq(CooperateSchoolCompany::getStatus, 1);
		//查未删除的
		queryWrapper.eq(CooperateSchoolCompany::getIsDeleted, 0);
		queryWrapper.eq(CooperateSchoolCompany::getSchoolId, schoolId);
		return cooperateSchoolCompanyMapper.selectCount(queryWrapper);
	}
}
